import { ref } from 'vue'
import dayjs, { Dayjs } from 'dayjs'
import _ from 'lodash-es'
import Api from '@/libs/api'
import Tool from '@/libs/utils/Tool'
import Enums from '@/datas/Enums'
import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import type { GoodsEditForm, ApiResponse, SaveResult } from './types'
import { useFormValidation } from './useFormValidation'

export const useGoodsFormSave = (editForm: Ref<GoodsEditForm>) => {
	const { t } = useI18n()
	const { validateAll } = useFormValidation()

	const doSave = async (): Promise<SaveResult> => {
		// 表单验证
		const validationResult = await validateAll(editForm.value)
		if (!validationResult.success) {
			Api.notify(validationResult.errors?.join('、') || '表单验证失败')
			return { success: false }
		}

		// 运费验证
		for (const index in editForm.value.freightInfo.remoteFreights) {
			const item = editForm.value.freightInfo.remoteFreights[index]
			if (!item.provinceId) {
				Api.notify(t('通知.追加运费省份不能为空'))
				return { success: false }
			}
			if (item.appendFreightPrice <= 0) {
				Api.notify(t('通知.追加运费必须大于0'))
				return { success: false }
			}
		}

		// 上传封面 && sort取值范围
		const uploadedMap: Record<string, any> = {}
		for (const index in editForm.value.skus) {
			const sku = editForm.value.skus[index]
			if (sku.sort < Enums.common.sortRange.min || sku.sort > Enums.common.sortRange.max) {
				Api.notify(
					t('通知.排序值超出范围', {
						min: Enums.common.sortRange.min,
						max: Enums.common.sortRange.max
					})
				)
				return { success: false }
			}
			if (sku.cover && sku.cover.substring(0, 5) == 'blob:') {
				const _sku = Tool.deepClone(sku)
				const coverStr = _sku.cover
				if (!uploadedMap[coverStr]) {
					const base64 = await Tool.blobToBase64(coverStr)
					const res = (await Api.post('/other/file/upload-by-base64', {
						base64
					})) as ApiResponse
					if (res.file) {
						uploadedMap[coverStr] = {
							abUrl: res.file.abUrl,
							id: res.file.id
						}
					}
				}
				sku.cover = uploadedMap[coverStr].abUrl
				sku.coverFileId = uploadedMap[coverStr].id
			}
		}

		const _editForm = Tool.deepClone(editForm.value)
		// 格式化日期区间
		_editForm.salesInfo.putOnSaleRange = editForm.value.salesInfo.putOnSaleRange.map(
			(date: Dayjs) => date.format('YYYY-MM-DD HH:mm')
		)

		// 如果是复制商品，使用添加商品的权限名称
		const permissionName =
			_editForm.permissionName === '商品库-商品管理-复制商品'
				? '商品库-商品管理-添加商品'
				: _editForm.permissionName

		const formParams = {
			editForm: JSON.stringify(_editForm),
			permissionName
		}

		const res = (await Api.post('/product/goods/add-or-edit', formParams)) as ApiResponse
		if (res.id) {
			Api.notify(t('通知.保存成功'))
			// 返回路由对象，由主组件处理跳转到商品详情页面
			return {
				success: true,
				id: res.id,
				route: {
					path: '/product/goods/info',
					query: { id: res.id }
				}
			}
		}
		return { success: false }
	}

	return {
		doSave
	}
}
